<template>
  <div class="login-register-view">
    <!-- 背景装饰 -->
    <div class="decoration-law"></div>

    <div class="login-register-container">
      <!-- 品牌标识 -->
      <div class="brand-header">
        <div class="logo">
          <el-icon><ScaleToOriginal /></el-icon>
          <span>在线法律支援平台</span>
        </div>
        <h2>专业法律支援，触手可及</h2>
      </div>

      <!-- 登录注册卡片 -->
      <div class="form-card">
        <!-- 选项卡切换 -->
        <div class="tabs">
          <button
            :class="['tab', activeTab === 'login' ? 'active' : '']"
            @click="activeTab = 'login'"
          >
            登录
          </button>
          <button
            :class="['tab', activeTab === 'register' ? 'active' : '']"
            @click="activeTab = 'register'"
          >
            注册
          </button>
        </div>

        <!-- 登录表单 -->
        <div v-if="activeTab === 'login'" class="form-content">
          <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="用户名或邮箱"
                size="large"
                :prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="密码"
                size="large"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <div class="remember-forgot">
              <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
              <a href="#" class="forgot-link" @click="handleUnfulfilled">忘记密码?</a>
            </div>
            <el-button
              type="primary"
              size="large"
              class="submit-btn"
              :loading="loading"
              @click="handleLogin"
            >
              登录
            </el-button>
          </el-form>

          <div class="divider">
            <span>或使用以下方式登录</span>
          </div>

          <div class="social-login">
            <el-button class="social-btn wechat" @click="handleUnfulfilled">
              <el-icon><ChatDotRound /></el-icon> 微信
            </el-button>
            <el-button class="social-btn phone" @click="handleUnfulfilled">
              <el-icon><Iphone /></el-icon> 手机
            </el-button>
          </div>
        </div>

        <!-- 注册表单 -->
        <div v-if="activeTab === 'register'" class="form-content">
          <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef">
            <el-form-item prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="用户名"
                size="large"
                :prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="realName">
              <el-input
                v-model="registerForm.realName"
                placeholder="真实姓名"
                size="large"
                :prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="email">
              <el-input
                v-model="registerForm.email"
                placeholder="邮箱地址"
                size="large"
                :prefix-icon="Message"
              />
            </el-form-item>
            <el-form-item prop="phone">
              <el-input
                v-model="registerForm.phone"
                placeholder="手机号码"
                size="large"
                :prefix-icon="Iphone"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="设置密码"
                size="large"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="确认密码"
                size="large"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item prop="agreement">
              <el-checkbox v-model="registerForm.agreement">
                我已阅读并同意 <a href="#" class="agreement-link">《服务条款》</a> 和
                <a href="#" class="agreement-link">《隐私政策》</a>
              </el-checkbox>
            </el-form-item>
            <el-button
              type="primary"
              size="large"
              class="submit-btn"
              :loading="loading"
              @click="handleRegister"
            >
              注册
            </el-button>
          </el-form>
        </div>
      </div>

      <!-- 返回首页链接 -->
      <div class="back-home">
        <el-button link @click="goToHome">
          <el-icon><ArrowLeft /></el-icon>
          返回首页
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, inject } from 'vue'
import { useRouter } from 'vue-router'
import { userInfoStore } from '@/stores/userinfo'
import {
  ScaleToOriginal,
  User,
  Lock,
  Message,
  Iphone,
  ChatDotRound,
  ArrowLeft,
  Flag,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = userInfoStore()
const activeTab = ref('login')
const loading = ref(false)

// 登录表单
const loginFormRef = ref()
const loginForm = reactive({
  username: '',
  password: '',
  remember: false,
})

const loginRules = reactive({
  username: [{ required: true, message: '请输入用户名或邮箱', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' },
  ],
})

// 注册表单
const registerFormRef = ref()
const registerForm = reactive({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  realName: '',
  agreement: false,
})

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

// 添加用户名格式验证
const validateUsername = (rule, value, callback) => {
  const usernamePattern = /^[a-zA-Z0-9_]{3,20}$/
  if (!usernamePattern.test(value)) {
    callback(new Error('用户名只能包含字母、数字和下划线，长度3-20位'))
  } else {
    callback()
  }
}

// 添加密码复杂度验证
const validatePassword = (rule, value, callback) => {
  const passwordPattern = /^(?=.*[a-zA-Z])(?=.*\d).{8,}$/
  if (!passwordPattern.test(value)) {
    callback(new Error('密码必须包含字母和数字，且长度不少于8位'))
  } else {
    callback()
  }
}

const registerRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { validator: validateUsername, trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' },
  ],
  confirmPassword: [{ required: true, validator: validatePass2, trigger: 'blur' }],
  agreement: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请同意服务条款和隐私政策'))
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
  ],
})

// 处理方法
const handleLogin = async () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await userStore.login({
          username: loginForm.username,
          password: loginForm.password,
        })

        ElMessage.success('登录成功')
        router.push('/')
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '登录失败,请重试')
      } finally {
        loading.value = false
      }

      // // 模拟登录过程
      // setTimeout(() => {
      //   loading.value = false
      //   ElMessage.success('登录成功')
      //   router.push('/')
      // }, 1000)
    }
  })
}

const handleRegister = async () => {
  registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true

      try {
        await userStore.register({
          username: registerForm.username,
          email: registerForm.email,
          phone: registerForm.phone,
          password: registerForm.password,
          realName: registerForm.realName,
        })

        ElMessage.success('注册成功,请登录')
        activeTab.value = 'login'

        Object.assign(registerForm, {
          username: '',
          email: '',
          phone: '',
          password: '',
          realName: '',
          confirmPassword: '',
          agreement: false,
        })
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '注册失败，请重试')
      } finally {
        loading.value = false
      }

      // // 模拟注册过程
      // setTimeout(() => {
      //   loading.value = false
      //   ElMessage.success('注册成功，请登录')
      //   activeTab.value = 'login'
      //   // 重置表单
      //   Object.assign(registerForm, {
      //     name: '',
      //     email: '',
      //     phone: '',
      //     password: '',
      //     confirmPassword: '',
      //     agreement: false,
      //   })
      // }, 1000)
    }
  })
}

const goToHome = () => {
  router.push('/')
}

const handleUnfulfilled = () => {
  ElMessage.warning('抱歉，该功能暂不可用')
}
</script>

<style scoped>
.login-register-view {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #1a3a5f 0%, #2c5282 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.decoration-law {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-image: url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M50 50L0 25L50 0L100 25L50 50Z' fill='%23ffffff' fill-opacity='0.03' fill-rule='evenodd'/%3E%3C/svg%3E");
  opacity: 0.1;
}

.login-register-container {
  width: 100%;
  max-width: 450px;
  z-index: 1;
}

.brand-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffd700;
  font-weight: bold;
  font-size: 24px;
  margin-bottom: 15px;
}

.logo .el-icon {
  margin-right: 10px;
  font-size: 28px;
}

.brand-header h2 {
  color: white;
  font-size: 1.2rem;
  font-weight: normal;
  margin: 0;
}

.form-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.tabs {
  display: flex;
  margin-bottom: 25px;
  border-bottom: 1px solid #eee;
}

.tab {
  flex: 1;
  padding: 12px;
  background: none;
  border: none;
  font-size: 16px;
  color: #666;
  cursor: pointer;
  position: relative;
  transition: all 0.3s;
}

.tab.active {
  color: #1a3a5f;
  font-weight: bold;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 3px;
  background: #ffd700;
  border-radius: 3px 3px 0 0;
}

.form-content {
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.forgot-link {
  color: #1a3a5f;
  text-decoration: none;
  font-size: 14px;
}

.forgot-link:hover {
  text-decoration: underline;
}

.submit-btn {
  width: 100%;
  background: linear-gradient(135deg, #1a3a5f 0%, #2c5282 100%);
  border: none;
  height: 48px;
  font-size: 16px;
  margin-bottom: 20px;
}

.submit-btn:hover {
  opacity: 0.9;
}

.divider {
  display: flex;
  align-items: center;
  margin: 20px 0;
  color: #999;
  font-size: 14px;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background: #eee;
}

.divider span {
  padding: 0 15px;
}

.social-login {
  display: flex;
  gap: 12px;
}

.social-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.social-btn.wechat {
  color: #2aae67;
  border-color: #2aae67;
}

.social-btn.wechat:hover {
  background: rgba(42, 174, 103, 0.1);
}

.social-btn.phone {
  color: #1a3a5f;
  border-color: #1a3a5f;
}

.social-btn.phone:hover {
  background: rgba(26, 58, 95, 0.1);
}

.agreement-link {
  color: #1a3a5f;
  text-decoration: none;
}

.agreement-link:hover {
  text-decoration: underline;
}

.back-home {
  text-align: center;
  margin-top: 20px;
}

.back-home .el-button {
  color: rgba(255, 255, 255, 0.8);
}

.back-home .el-button:hover {
  color: #ffd700;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #eee inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #1a3a5f inset;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #1a3a5f;
  border-color: #1a3a5f;
}

:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #1a3a5f;
}
</style>
